#include "DDCPItemFactory.hpp"


CDDCPItemManager* CDDCPItemManager::s_manager = NULL;

CDDCPItemManager::CDDCPItemManager(){
    //DDCP_CLASSREGISTER(Action, this);
    //DDCP_CLASSREGISTER(Response, this);
}

CDDCPItemManager::~CDDCPItemManager(){
    std::map<char*, CDDCPItemAbstractFactory*>::iterator it;
    it = m_regTable.begin();
    for (;it != m_regTable.end(); it++){
        CDDCPItemAbstractFactory* tmp = it->second;
        if (tmp){
            delete tmp;
            it->second = NULL;
        }
    }
    m_regTable.clear();
}

CDDCPItemManager* CDDCPItemManager::instance(){
    if (!s_manager){
        s_manager = new CDDCPItemManager();
    }
    return s_manager;
}

bool CDDCPItemManager::Register(char* classEnum, CDDCPItemAbstractFactory* fact){
    if(!classEnum || !fact)
        return false;
    
    bool ret = false;
    std::map<char*, CDDCPItemAbstractFactory*>::iterator it;

    it = m_regTable.find(classEnum);
    if (it != m_regTable.end()){
        if(fact) delete fact;
        ret = false;
    } else{
        m_regTable.insert(std::pair<char*, CDDCPItemAbstractFactory*>(classEnum, fact));
        ret = true;
    }

    return ret;
}

bool CDDCPItemManager::unRegister(char* classEnum){
    if(!classEnum)
        return false;

    bool ret = false;
    std::map<char*, CDDCPItemAbstractFactory*>::iterator it;

    it = m_regTable.find(classEnum);
    if (it != m_regTable.end()){
        CDDCPItemAbstractFactory* tmp = it->second;
        if(tmp){
            delete tmp;
            m_regTable.erase(it);
        }
        ret = true;
    }

    return ret;
}

CDDCPItem* CDDCPItemManager::creat(char* classEnum){
    if(!classEnum)
        return NULL;

    CDDCPItem* item = NULL;
    std::map<char*, CDDCPItemAbstractFactory*>::iterator it;
    it = m_regTable.find(classEnum);
    if (it != m_regTable.end()){
        item = (CDDCPItem*)it->second->creat();
    }

    return item;
}

